package com.daocao.hua.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.constant.Const;
import com.daocao.hua.event.OnChsiRegisterEventMsg;
import com.daocao.hua.impl.ChsiInfoImpl;
import com.daocao.hua.http.InfoCallBack;
import com.daocao.hua.model.ChsiRegisterModel;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.JsonUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.CircularProgress;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

/**
 * 学信网注册界面
 * Created by Master.Dong on 16/4/10.
 */
public class ChsiRegisterActivity extends BaseActivity implements View.OnClickListener {

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CircularProgress loading;
    private ImageView mIv;
    private Bitmap bitmap;
    private TextView okBtn, forget, agree;
    private LinearLayout view1, view2, imgCodeView;
    private EditText mPhone, mImgCode, mCode, mRealname, mIdno, mPassword;
    private TextView codebtn1;
    private ImageView imgCode;
    private CheckBox mSee, cb;
    private boolean isSend;
    private int viewIndex = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.chsi_register_activity);
        baseInitView(this, "ChsiRegisterActivity", Const.ViewType.ACTIVITY);
        initView();

    }

    private void initView() {

        setTitleText(getString(R.string.register_chsi2));
        getLeftImgBtn().setOnClickListener(this);
        mIv = (ImageView) findViewById(R.id.chsi_iv);
        bitmap = ImageUtil.readBitMap(this, R.mipmap.chsi);
        mIv.setImageBitmap(bitmap);
        cb = (CheckBox) findViewById(R.id.cb);
        loading = (CircularProgress) findViewById(R.id.progressBar);
        agree = (TextView) findViewById(R.id.agree);
        forget = (TextView) findViewById(R.id.forget);
        okBtn = (TextView) findViewById(R.id.ok);
        view1 = (LinearLayout) findViewById(R.id.view1);
        view2 = (LinearLayout) findViewById(R.id.view2);
        imgCodeView = (LinearLayout) findViewById(R.id.img_code_view);
        mPhone = (EditText) findViewById(R.id.e_phone1);
        mImgCode = (EditText) findViewById(R.id.i_code1);
        mCode = (EditText) findViewById(R.id.t_code1);
        mRealname = (EditText) findViewById(R.id.e_realname2);
        mIdno = (EditText) findViewById(R.id.idno2);
        mPassword = (EditText) findViewById(R.id.e_password2);
        codebtn1 = (TextView) findViewById(R.id.b_code1);
        imgCode = (ImageView) findViewById(R.id.code_iv);
        mSee = (CheckBox) findViewById(R.id.see);


        imgCode.setOnClickListener(this);
        codebtn1.setOnClickListener(this);
        agree.setOnClickListener(this);
        forget.setOnClickListener(this);
        okBtn.setOnClickListener(this);

        StringBuilder sb = new StringBuilder();
        sb.append(getResources().getString(R.string.read_and_agree));
        sb.append("<font color='#e3483d'>");
        sb.append(getResources().getString(R.string.service_clause));
        sb.append("</font>");
        Spanned spanned = Html.fromHtml(sb.toString());
        agree.setText(spanned);

        mPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    if (checkMobile())
                        getCheckMobile();
                } else imgCodeView.setVisibility(View.GONE);
            }
        });

        mSee.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mSee.setBackgroundResource(R.mipmap.see_off);
                    mPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); //显示密码
                } else {
                    mSee.setBackgroundResource(R.mipmap.see);
                    mPassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); //隐藏密码
                }
                mPassword.setSelection(mPassword.getText().length());
            }
        });

    }

    /**
     * 显示的界面
     *
     * @param index
     */
    private void showView(int index) {
        if (index == 2) {  //显示界面二
            viewIndex = 2;
            view1.setVisibility(View.GONE);
            view2.setVisibility(View.VISIBLE);
            forget.setVisibility(View.GONE);
            okBtn.setText(getString(R.string.finish));
        } else {  //显示界面一
            viewIndex = 1;
            view1.setVisibility(View.VISIBLE);
            view2.setVisibility(View.GONE);
            forget.setVisibility(View.VISIBLE);
            okBtn.setText(getString(R.string.next));
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                if (viewIndex == 2) {
                    showView(1);
                } else ChsiRegisterActivity.this.finish();
                break;
            case R.id.ok:
                if (!cb.isChecked())
                    ToastUtil.makeText(this, getResources().getString(R.string.please_agree_server), Toast.LENGTH_SHORT).show();
                else {
                    if (view1.getVisibility() == View.VISIBLE) {
                        if (checkMobile() && checkCode()) {
                            showView(2);
                        }
                    } else if (view2.getVisibility() == View.VISIBLE) {
                        if (checkView2Input())
                            getRegisterInfo(mPhone.getText().toString(), mCode.getText().toString(), mRealname.getText().toString(), mIdno.getText().toString(), mPassword.getText().toString());
                    }
                }
                break;
            case R.id.forget:
                ChsiRegisterActivity.this.finish();
                Util.startActivity(this, ChsiForgetPwdActivity.class);
                break;
            case R.id.agree:
                Intent intent = new Intent(this, AboutActivity.class);
                intent.putExtra("id", Const.ContractType.CHSI);
                intent.putExtra("type", 1);
                intent.putExtra("title", getResources().getString(R.string.service_contract_text2));
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.b_code1:
                if (imgCodeView.getVisibility() == View.GONE) {
                    if (checkMobile())
                        getCheckMobile();
                } else {
                    if (checkMobile() && checkImgCode()) {
                        timer.start();
                        getCodeInfo();
                    }
                }
                break;
            case R.id.code_iv:
                getImgCode();
                break;
        }
    }

    /**
     * 验证码计时器
     */
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            codebtn1.setEnabled(false);
            codebtn1.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
            codebtn1.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        codebtn1.setEnabled(true);
        if (isSend)
            codebtn1.setText(getResources().getString(R.string.send_code_again));
        else
            codebtn1.setText(getResources().getString(R.string.get_code));
        codebtn1.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
        ImageUtil.releaseImageViewResouce(mIv);
    }

    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (b) {
            imgCode.setEnabled(false);
            forget.setEnabled(false);
            agree.setEnabled(false);
            okBtn.setEnabled(false);
            if (loading != null) loading.setVisibility(View.VISIBLE);
        } else {
            imgCode.setEnabled(true);
            forget.setEnabled(true);
            agree.setEnabled(true);
            okBtn.setEnabled(true);
            if (loading != null) loading.setVisibility(View.GONE);
        }
    }

    /**
     * 验证手机号
     *
     * @return
     */
    private boolean checkMobile() {
        if (TextUtils.isEmpty(mPhone.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.phone_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!Util.isMobileNO(mPhone.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.phone_is_error2), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查验证码
     *
     * @return
     */
    private boolean checkImgCode() {
        if (TextUtils.isEmpty(mImgCode.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.img_code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查验证码
     *
     * @return
     */
    private boolean checkCode() {
        if (TextUtils.isEmpty(mCode.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.sms_code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查姓名、身份证、密码非空
     *
     * @return
     */
    private boolean checkView2Input() {
        if (TextUtils.isEmpty(mRealname.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.realname_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(mIdno.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.idcard_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(mPassword.getText().toString().trim())) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.password_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (mPassword.getText().toString().trim().length() < 6) {
            ToastUtil.makeText(ChsiRegisterActivity.this, getString(R.string.pwd_is_under_6), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 验证手机号
     */
    private void getCheckMobile() {
        showLoading(true);
        new ChsiInfoImpl().getCheckMobileInfo(this, mPhone.getText().toString().trim(), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                if (o.toString().equals("true")) {
                    imgCodeView.setVisibility(View.VISIBLE);
                    getImgCode();
                } else
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.mobile_already_register), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 获取图形验证码
     */
    private void getImgCode() {
        mImgCode.setText("");
        showLoading(true);
        new ChsiInfoImpl().getImgCodeInfo(this, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                Bitmap bitmap = (Bitmap) o;
                imgCode.setImageBitmap(bitmap);
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取短信验证码
     */
    private void getCodeInfo() {
        showLoading(true);
        new ChsiInfoImpl().getCodeInfo(this, mPhone.getText().toString().trim(), mImgCode.getText().toString().trim(), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                ChsiRegisterModel model = JsonUtil.fromJson(o.toString(), ChsiRegisterModel.class);
//                RBLog.i("----  ", model.getStatus() + "    " + model.getTips() + "   " + model.getTipsNote() + "    " + model.getTipsBtnValue());

                String tips = model.getTips();
                if (model.getStatus().equals("0")) {
                    if (tips.contains("[") && tips.contains("]")) {
                        ToastUtil.makeText(getApplicationContext(), tips.substring(tips.indexOf("[") + 1, tips.lastIndexOf("]")), Toast.LENGTH_SHORT).show();
                        if (tips.contains(getString(R.string.code1))) getImgCode();
                    }
                    resetBtn();
                } else if (model.getStatus().equals("2")) {
                    isSend = true;
                    ToastUtil.makeText(getApplicationContext(), tips, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                resetBtn();
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取注册信息
     */
    private void getRegisterInfo(String phone, String code, String realname, String idno, String password) {
        showLoading(true);
        new ChsiInfoImpl().getRegisterInfo(this, phone, code, realname, idno, password, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                showLoading(false);
                if (o.toString().contains(getString(R.string.idno_already_register)))
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.idno_already_register), Toast.LENGTH_SHORT).show();
                else if (o.toString().contains(getString(R.string.idno_is_error)))
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.idno_is_error), Toast.LENGTH_SHORT).show();
                else if (o.toString().contains(getString(R.string.code_is_error)))
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_error), Toast.LENGTH_SHORT).show();
                else if (o.toString().contains(getString(R.string.register_success))) {
                    ToastUtil.makeText(getApplicationContext(), getString(R.string.register_success), Toast.LENGTH_SHORT).show();
                    sendRegisterEvent();
                }
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 发送 注册成功 事件
     */
    private void sendRegisterEvent() {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mPhone.getText().toString().trim());
        EventBus.getDefault().post(new OnChsiRegisterEventMsg(map));
        ChsiRegisterActivity.this.finish();
    }

}
